<template>
  <div class="ranking-box newproduct-ranking">
    <div class="ranking-header">
      <h3>好评榜</h3>
    </div>
    <div v-if="loading" class="ranking-loading">加载中...</div>
    <div v-else-if="error" class="ranking-error">{{ error }}</div>
    <div v-else class="ranking-content">
      <div
        v-for="(item, index) in rankingList"
        :key="item.productId"
        class="ranking-item"
        @click="handleItemClick(item)"
      >
        <div class="rank-number">{{ item.rank }}</div>
        <div class="item-info">
          <div class="item-name">{{ item.productName }}</div>
          <div class="item-price">¥{{ item.price }}</div>
        </div>
      </div>
      <div v-if="rankingList.length === 0" class="no-data">暂无数据</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getNewProductRanking } from '@/api'

const router = useRouter()
const rankingList = ref([])
const loading = ref(false)
const error = ref('')

const loadRanking = async () => {
  if (loading.value) return // 防止重复加载
  loading.value = true
  error.value = ''
  try {
    const response = await getNewProductRanking(3)
    if (response && (response.code === 200 || response.code === 0)) {
      rankingList.value = Array.isArray(response.data) ? response.data : []
    } else {
      error.value = (response && response.message) || '加载失败'
      rankingList.value = []
    }
  } catch (err) {
    error.value = '加载失败，请稍后重试'
    rankingList.value = []
    console.error('加载新品榜失败:', err)
  } finally {
    loading.value = false
  }
}

const handleItemClick = (item) => {
  router.push(`/iteminfo/${item.productId}`)
}

onMounted(() => {
  loadRanking()
})
</script>

<style scoped>
.ranking-box {
  background: #fff3e0;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  min-height: 200px;
}

.ranking-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #f57c00;
}

.ranking-loading,
.ranking-error {
  text-align: center;
  padding: 20px;
  color: #666;
}

.ranking-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.ranking-item:hover {
  background: #f5f5f5;
}

.rank-number {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f57c00;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 13px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.item-price {
  font-size: 14px;
  color: #e53935;
  font-weight: 600;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>

